package com.mark.util;

import org.apache.commons.io.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by macmatilda on 16/4/26.
 */
public class CommonUtil {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
    private static SimpleDateFormat simpleDateFormatChat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat simpleDateFormatDetail = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static AtomicLong index = new AtomicLong(1888);

    public static String createRandomId() {
        index.compareAndSet(8889, 1888);
        return String.format("ID%s%04d", simpleDateFormat.format(Calendar.getInstance().getTime()), index.getAndIncrement());
    }

    public static String convertFile2String(String path) {
        try {
            byte[] bytes = FileUtils.readFileToByteArray(new File(path));
            byte[] encoded = Base64.getEncoder().encode(bytes);
            String encodedString = new String(encoded);
            System.out.println(encodedString);
            return encodedString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File convertString2File(String base64String) {
        try {
            File tempFile = File.createTempFile("image", ".jpg", new File("."));
            byte[] bytes = Base64.getDecoder().decode(base64String.getBytes());
            FileUtils.writeByteArrayToFile(tempFile, bytes);
            return tempFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isEmpty(String string) {
        return string == null || string.trim().length() == 0;
    }

    public static String throwableToString(Throwable throwable) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(byteArrayOutputStream);
        throwable.printStackTrace(printStream);
        String content = byteArrayOutputStream.toString();
        return content;
    }

    public static String getDateString() {
        return simpleDateFormatDetail.format(Calendar.getInstance().getTime());
    }

    public static List<String> getHostIPAddressList() {
        List<String> ipAddressList = new ArrayList<>();
        Enumeration netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress inetAddress = null;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) netInterfaces.nextElement();
                Enumeration inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = (InetAddress) inetAddresses.nextElement();
                    if (inetAddress.getHostAddress().indexOf(":") == -1) {
                        ipAddressList.add(inetAddress.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipAddressList;
    }

    public static String createRandomString(int length) {
        String rangeString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();

        for (int i = 0; i < length; i++) {
            int randomInt = random.nextInt(rangeString.length());
            stringBuffer.append(rangeString.charAt(randomInt));
        }

        return stringBuffer.toString();
    }

    public static String encodeSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

    public static long timestrampLong() {
        return System.currentTimeMillis() / 1000;
    }

    public static String timestamp() {
        return String.valueOf(timestrampLong());
    }

    public static String createRandom32String() {
//        String string = UUID.randomUUID().toString();
//        return string.replaceAll("-", "");
        return createRandomString(32);
    }

    private static String xml = "<xml>\n" +
        "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
        "   <return_msg><![CDATA[OK]]></return_msg>\n" +
        "   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>\n" +
        "   <mch_id><![CDATA[10000100]]></mch_id>\n" +
        "   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>\n" +
        "   <openid><![CDATA[oUpF8uMuAJO_M2pxb1Q9zNjWeS6o]]></openid>\n" +
        "   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>\n" +
        "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
        "   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>\n" +
        "   <trade_type><![CDATA[JSAPI]]></trade_type>\n" +
        "</xml>";

    public final static String md5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String removeBase64UrlPrefix(String url) {
        url = url.replaceFirst("^data:image\\/\\w+;base64,", "");
        return url;
    }

    public static String addBase64UrlPrefix(String url) {
        url = removeBase64UrlPrefix(url);
        url = "data:image/png;base64," + url;
        return url;
    }

    public static String convertImage2Base64(String path) {
        String base64String = CommonUtil.convertFile2String(path);
        base64String = CommonUtil.addBase64UrlPrefix(base64String);
        return base64String;
    }

    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    public static int getDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }

    public static InputStream readResource(String resource){
        return CommonUtil.class.getClassLoader().getResourceAsStream(resource);
    }
}
